import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from "rxjs";


@Injectable()
export class ArticleService {

    private articlePool;//文章数据
    constructor(
        private http: HttpClient
    ) {
        this.articlePool=[];
        //通过异步任务拉取全部文章数据
        this.getArticles();
    }

    //文章数据
    getArticle(body: any): Observable<any> {
        return this.http.request('get', '/api/article', {body: body});
    }

    //所有文章
    getArticleList(): Observable<any> {
        return this.http.request('get', '/api/articleList');
    }

    //将获取到的文章推入文章池中
    setArticlePool(article:any){
        if(this.articlePool[article.id])return;

        this.articlePool[article.id]=article;

    }

    //从文章池中获取文章数据
    getArticleFromPool(articleId:number) {
        if (!this.articlePool[articleId]) return;
        return this.articlePool[articleId];
    }

    //这个函数为异步向后端获取全部的文章数据,推入缓存池中
    getArticles(){
        this.http.request('get', '/api/articles').subscribe((data:any)=>{
            if(data.status_code!=200)return;

            for( let article of data.result){
                this.setArticlePool(article);
            }

        });
    }



}
